package rent_service

import "repairs/models"

type RentRecord struct {
	ID        int
	UserID    int
	Room      string
	StartTime int64
	EndTime   int64

	PageNum  int
	PageSize int

	StartRange [2]int64
	EndRange   [2]int64
}

func (r *RentRecord) Add(rentKey string) error {
	rent := map[string]interface{}{
		"user_id":    r.UserID,
		"room":       r.Room,
		"start_time": r.StartTime,
		"end_time":   r.EndTime,
		"rent_key":   rentKey,
	}
	err := models.AddRent(rent)
	return err
}

func (r *RentRecord) ExistById() (bool, error) {
	return models.ExistRentById(r.ID)
}

func (r *RentRecord) ExistByRoom() (bool, error) {
	return models.ExistRentByRoom(r.Room, r.StartTime, r.EndTime)
}

func (r *RentRecord) GetUserRent() (models.RentRecord, error) {
	return models.GetRentByUser(r.UserID)
}

func (r *RentRecord) GetAll() ([]*models.RentRecord, error) {
	rents, err := models.GetRents(r.PageNum, r.PageSize, r.getMaps())
	if err != nil {
		rents = nil
	}
	return rents, err
}

func (r *RentRecord) Delete() error {
	return models.DeleteRent(r.ID)
}

func (r *RentRecord) Count() (int, error) {
	return models.GetRentTotal(r.getMaps())
}

func (r *RentRecord) getMaps() map[string]interface{} {
	maps := make(map[string]interface{})
	maps["deleted_on"] = 0
	if r.UserID != 0 {
		maps["user_id"] = r.UserID
	}
	if r.Room != "" {
		maps["room"] = r.Room
	}
	if r.StartRange[0] != r.StartRange[1] {
		maps["start_range"] = r.StartRange
	}
	if r.EndRange[0] != r.EndRange[1] {
		maps["end_range"] = r.EndRange
	}
	return maps
}
